# include <stdlib.h>  
# include <stdio.h>  
# include <mysql.h>
# include "cvpn_mysql.h"

//init mysql and connect mysql
int cvpn_mysql_init(MYSQL *conn_ptr, const char *host, const char *user, const char *pwd, const char *db) {  
    
    if (!mysql_init(conn_ptr)) {  
        fprintf(stderr, "mysql_init failed\n");  
        return EXIT_FAILURE;  
    }  
    if (mysql_real_connect(conn_ptr, host, user, pwd, db, 0, NULL, 0)) {  
        printf("Connection success\n"); 
    } else {  
        fprintf(stderr, "Connection failed\n");  
    }  
    return EXIT_SUCCESS;  
}  
//close MYSQL
int cvpn_mysql_close(MYSQL *conn_ptr){
    mysql_close(conn_ptr);  
    return EXIT_SUCCESS;
}

//selct mysql
int cvpn_mysql_select(MYSQL *conn_ptr, const char *sql){

    MYSQL_RES *res_ptr;  
    MYSQL_ROW sqlrow;  
    MYSQL_FIELD *fd; 
    int res, i, j;  
    int cvpn_yes = 1;
    res = mysql_query(conn_ptr, sql);//查询语句  
    if (res) {         
        printf("SELECT error:%s\n",mysql_error(conn_ptr));     
        cvpn_yes = 0;
    } else {        
        res_ptr = mysql_store_result(conn_ptr);             //取出结果集  
        if(res_ptr) {               
            printf("%lu Rows\n",(unsigned long)mysql_num_rows(res_ptr));   
            j = mysql_num_fields(res_ptr);          
            while((sqlrow = mysql_fetch_row(res_ptr)))  {   //依次取出记录  
                for(i = 0; i < j; i++)         
                    printf("%s\t", sqlrow[i]);              //输出  
                printf("\n");          
            }              
            if (mysql_errno(conn_ptr)) {                      
                fprintf(stderr,"Retrive error:s\n",mysql_error(conn_ptr));             
                cvpn_yes = 0;
            }        
        }        
        mysql_free_result(res_ptr);        
    }
    
    if (cvpn_yes == 1){
       return EXIT_SUCCESS; 
    }
    else {
        return EXIT_FAILURE;
    }
    
}
//insert and update and delete
int cvpn_mysql_execute(MYSQL *conn_ptr, const char *sql){
    int res; 
    int cvpn_yes = 1;
    res = mysql_query(conn_ptr, sql);   
    if (!res) {     //输出受影响的行数  
        printf("%lu rows affected\n",(unsigned long)mysql_affected_rows(conn_ptr));   
    } else {       //打印出错误代码及详细信息  
        fprintf(stderr, "Insert error %d: %sn",mysql_errno(conn_ptr),mysql_error(conn_ptr));
        cvpn_yes = 0;
    }   
    if (cvpn_yes == 1){
        return EXIT_SUCCESS;
    }
    else {
        return EXIT_FAILURE;
    }

}

